package com.example.szys.controler;

import com.example.szys.POJO.HttpResult;
import com.example.szys.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.szys.model.User;

import java.util.List;

@RestController
public class UserControler {
    @Autowired
    private UserRepository userRepository;


    @GetMapping(value = "/users")
    public List<User> userList(){
        return userRepository.findAll();
    }

    @PostMapping(value = "/registuser")
    public HttpResult<User> registUser(@RequestParam("email") String email,@RequestParam("password") String psw){//注册
        HttpResult<User> userHttpResult=new HttpResult<>();
        User u=new User();
        if(userRepository.findOne(email)!=null){
            userHttpResult.setResult(HttpResult.RESULT_FAIL);
            return userHttpResult;
        }else {
            u.setEmail(email);
            u.setPassword(psw);
            userRepository.save(u);
            userHttpResult.setResult(HttpResult.RESULT_SUCCESS);
            return userHttpResult;
        }
    }

    @PostMapping(value = "login")
    public HttpResult<User> login(@RequestParam("email") String email, @RequestParam("password") String psw){//登陆
        HttpResult<User> userHttpResult=new HttpResult<>();
        userHttpResult.setResult(HttpResult.RESULT_FAIL);
        if(userRepository.findOne(email)!=null){
            User user=userRepository.findOne(email);
            if(user.getPassword().equals(psw)){
                userHttpResult.setResult(HttpResult.RESULT_SUCCESS);
                userHttpResult.setContent(user);
            }
        }
        return userHttpResult;
    }

    @PostMapping(value = "resetpsw")
    public HttpResult<User> resetpsw(@RequestParam("email") String email,@RequestParam("password") String psw){//重置密码
        HttpResult<User> userHttpResult=new HttpResult<>();
        User u;
        if(userRepository.findOne(email)==null){
            userHttpResult.setResult(HttpResult.RESULT_FAIL);
            return userHttpResult;
        }
        u=userRepository.findOne(email);
        u.setPassword(psw);
        userRepository.save(u);
        userHttpResult.setResult(HttpResult.RESULT_SUCCESS);
        return userHttpResult;
    }

    @PostMapping(value = "/editinfo")
    public HttpResult<User> editInfo(@RequestParam("email") String email,@RequestParam("name") String name,@RequestParam("school") String school,@RequestParam("sex") boolean sex,@RequestParam("age") int age){
        HttpResult<User> userHttpResult=new HttpResult<>();
        User u;
        u=userRepository.findOne(email);
        u.setName(name);
        u.setSchool(school);
        u.setSex(sex);
        u.setAge(age);
        userHttpResult.setResult(HttpResult.RESULT_SUCCESS);
        userHttpResult.setContent(userRepository.save(u));
        return userHttpResult;
    }

}
